package com.sun.designpatternsdemo.observer.bean

import android.util.Log
import java.util.*
import kotlin.collections.ArrayList


/**
 * 版权：xx公司 版权所有
 * @author sun
 * 版本：1.0
 * 创建日期：2021/6/28 17:18
 * 描述：模拟使用者
 *
 */
class ObserverUser1(subject: Subject) : Observer {
    override fun update(msg: String) {
        Log.e("-----ObserverUser1 ", "得到 3D 号码:$msg, 我要记下来。 ")
        //        Toast.makeText(PatternApplication.getInstance(), "-----ObserverUser1 得到 3D 号码:" + msg, Toast.LENGTH_SHORT).show();
    }

    init {
        subject.registerObserver(this)
    }
}


class ObserverUser2(subject: Subject) : Observer {
    init {
        subject.registerObserver(this)
    }

    override fun update(msg: String) {
        Log.e("-----ObserverUser2 ", "得到 3D 号码:$msg, 我要告诉舍友们。")
    }
}

class SubjectFor3d : Observable() {
    /**
     * 更新主题消息
     */
    var msg: String? = null
        set(msg) {
            field = msg
            setChanged()
            notifyObservers()
        }
}

class SubjectForSSQ : Observable() {
    /**
     * 更新主题消息
     */
    var msg: String? = null
        set(msg) {
            field = msg
            setChanged()
            notifyObservers()
        }
}

class Observer1 : java.util.Observer {
    fun registerSubject(observable: Observable) {
        observable.addObserver(this)
    }

    override fun update(o: Observable?, arg: Any?) {
        if (o is SubjectFor3d) {
            val subjectFor3d = o
            Log.e("SubjectFor3d:", "subjectFor3d's msg -- >" + subjectFor3d.msg)
        }
        if (o is SubjectForSSQ) {
            val subjectForSSQ = o
            Log.e("SubjectForSSQ:", "subjectForSSQ's msg -- >" + subjectForSSQ.msg)
        }

    }

}

class ObjectFor3D : Subject {
    private val observers = ArrayList<Observer>()
    var msg: String? = null
        set(msg) {
            field = msg
            notifyObservers()
        }

    override fun registerObserver(observer: Observer) {
        observers.add(observer)
    }

    override fun removeObserver(observer: Observer) {
        val index = observers.indexOf(observer)
        if (index >= 0) {
            observers.removeAt(index)
        }
    }

    override fun notifyObservers() {
        for (observer in observers){
            observer.update(msg!!)
        }
//        observers.forEach {
//            it.update(msg!!)
//        }
    }

}